package com.guslegend.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.guslegend.config.OSSConfig;
import com.guslegend.service.FileService;
import com.guslegend.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author: guslegend
 * @description: 文件上传
 * @create: 2025-05-27 20:33
 **/
@Slf4j
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String uploadUserHeadImg(MultipartFile file) {
        String imgUrl = "";
//        获取oss配置
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        String bucketName = ossConfig.getBucketName();
        //创建oss对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //        拿到文件原始名
        String originalFilename = file.getOriginalFilename();
        //        拿到文件后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //日期格式化
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        //        根据年月日存储文件
        String floder = dateTimeFormatter.format(LocalDateTime.now());
        //拼接新文件名
        String newFileName = "user/" + floder + "/" + CommonUtil.getUUID() + extension;
        //        oss存储
        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, newFileName, file.getInputStream());
            if (putObjectResult != null) {
                imgUrl = "https://" + bucketName + "." + endpoint + "/" + newFileName;
            }
        } catch (IOException e) {
            log.error("文件上传失败！ {}", e);
            e.printStackTrace();
        } finally {
//            关闭ossClient 不然会造成内存的泄露
            ossClient.shutdown();
        }
        return imgUrl;
    }
}

